<template>
    <div class="min-h-screen bg-gradient-to-br from-[#E8F1FF] to-[#C5DCFF] p-8">
      <div class="max-w-6xl mx-auto">
        <h1 class="text-4xl font-bold text-[#306BAC] mb-8 text-center">
          我的知识书柜
        </h1>
        <div class="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 gap-6">
          <div v-for="doc in documents" :key="doc.id" class="group perspective">
            <div class="relative bg-white rounded-lg shadow-md p-4 h-56 flex flex-col justify-between transition-all duration-300 transform group-hover:rotate-y-10 group-hover:shadow-xl">
              <div class="text-center">
                <div class="w-20 h-20 mx-auto mb-3 bg-[#E8F1FF] rounded-full flex items-center justify-center">
                  <FileTextIcon class="w-12 h-12 text-[#306BAC]" />
                </div>
                <h3 class="text-sm font-medium text-[#306BAC] line-clamp-2">{{ doc.title }}</h3>
              </div>
              <div class="text-xs text-[#6F9CEB]">上传日期: {{ doc.uploadDate }}</div>
              <div class="absolute inset-0 bg-gradient-to-br from-[#306BAC] to-[#6F9CEB] rounded-lg flex items-center justify-center opacity-0 group-hover:opacity-95 transition-opacity duration-300">
                <button @click="startLearning(doc.id)" class="bg-white text-[#306BAC] px-3 py-1 rounded-full text-sm font-medium mr-2 hover:bg-[#E8F1FF] transition-colors duration-300 transform hover:scale-105">
                  开始学习
                </button>
                <button @click="confirmDelete(doc.id)" class="bg-red-500 text-white px-3 py-1 rounded-full text-sm font-medium hover:bg-red-600 transition-colors duration-300 transform hover:scale-105">
                  删除资料
                </button>
              </div>
            </div>
          </div>
          <div @click="uploadDocument" class="group perspective">
            <div class="bg-white rounded-lg shadow-md p-4 h-56 flex items-center justify-center cursor-pointer transition-all duration-300 transform group-hover:rotate-y-10 group-hover:shadow-xl group-hover:bg-[#E8F1FF]">
              <PlusCircleIcon class="w-20 h-20 text-[#6F9CEB] group-hover:text-[#306BAC] transition-colors duration-300" />
            </div>
          </div>
        </div>
        <ShowMessage ref="messageRef" />
        <div v-if="uploading" class="fixed inset-0 flex items-center justify-center bg-black bg-opacity-50 z-50">
          <div class="bg-white rounded-lg p-6 w-80">
            <h3 class="text-xl font-semibold text-[#306BAC] mb-4">文档上传中...</h3>
            <div class="relative pt-1">
              <div class="overflow-hidden h-2 text-xs flex rounded bg-[#E8F1FF]">
                <div :style="{ width: uploadProgress + '%' }" class="shadow-none flex flex-col text-center whitespace-nowrap text-white justify-center bg-[#306BAC]"></div>
              </div>
              <div class="text-right">
                <span class="text-[#6F9CEB] text-xs font-semibold inline-block">{{ uploadProgress }}%</span>
              </div>
            </div>
          </div>
        </div>
        <ConfirmDialog 
          :show="showConfirmDelete"
          :title="'确认删除资料吗?'"
          :message="'删除后将无法恢复,请谨慎操作。'"
          @confirm="deleteDocument"
          @cancel="cancelDelete"
        />
      </div>
    </div>
  </template>
  
  <script setup>
  import { ref, onMounted } from 'vue';
  import { FileTextIcon, PlusCircleIcon } from 'lucide-vue-next';
  import { useRouter } from 'vue-router';
  import ShowMessage from '@/components/share/showMessage.vue';
  import axiosClient from '@/utils/axios';
  import ConfirmDialog from '@/components/share/confirmDialog.vue';
  
  const router = useRouter();
  const documents = ref([]);
  const messageRef = ref(null);
  const uploading = ref(false);
  const uploadProgress = ref(0);
  const showConfirmDelete = ref(false);
  const deleteDocId = ref(null);
  
  // 获取所有文档
  const fetchDocuments = async () => {
    try {
      const response = await axiosClient.get(`/materials/`, {withCredentials:true});
      documents.value = response.data.map(doc => ({
        id: doc.id,
        title: doc.title,
        uploadDate: new Date(doc.created_at).toLocaleDateString()
      }));
      messageRef.value?.showMessage('获取文档列表成功', 'INFO');
    } catch (error) {
      messageRef.value?.showMessage('获取文档列表失败', 'BUG');
    }
  };
  
  // 开始学习
  const startLearning = (docId) => {
    router.push(`/readTask/${docId}`);
  };
  
  // 显示删除确认框
  const confirmDelete = (docId) => {
    deleteDocId.value = docId;
    showConfirmDelete.value = true;
  };
  
  // 取消删除
  const cancelDelete = () => {
    deleteDocId.value = null;
    showConfirmDelete.value = false;
  };
  
  // 确认删除文档
  const deleteDocument = async () => {
    try {
      await axiosClient.delete(`/materials/${deleteDocId.value}`, { withCredentials: true });
      documents.value = documents.value.filter(doc => doc.id !== deleteDocId.value);
      messageRef.value?.showMessage('文档删除成功', 'INFO');
    } catch (error) {
      console.error('删除文档错误:', error);
      messageRef.value?.showMessage('删除文档失败', 'BUG');
    }
    deleteDocId.value = null;
    showConfirmDelete.value = false;
  };
  
  // 上传文档
  const uploadDocument = () => {
    // 创建文件输入元素
    const input = document.createElement('input');
    input.type = 'file';
    input.accept = '.pdf';
    
    input.onchange = async (e) => {
      const file = e.target.files[0];
      if (!file) return;

      const formData = new FormData();
      formData.append('file', file);
      formData.append('title', file.name); 

      try {
        uploading.value = true;
        await axiosClient.post(
          `/materials/`,
          formData,
          {
            headers: {
              'Content-Type': 'multipart/form-data',
            },
            withCredentials: true,
            onUploadProgress: (progressEvent) => {
              uploadProgress.value = Math.round((progressEvent.loaded * 100) / progressEvent.total);
            },
          }
        );
        
        // 上传成功后重新获取文档列表
        await fetchDocuments();
        messageRef.value?.showMessage('文档上传成功', 'INFO');
      } catch (error) {
        console.error('上传文档错误:', error);
        messageRef.value?.showMessage('上传文档失败', 'BUG');
      } finally {
        uploading.value = false;
        uploadProgress.value = 0;
      }
    };

    input.click();
  };

  // 组件挂载时获取文档列表
  onMounted(() => {
    fetchDocuments();
  });
  </script>
  
  <style scoped>
  .perspective {
    perspective: 1000px;
  }
  
  .rotate-y-10 {
    transform: rotateY(10deg);
  }
  
  @keyframes float {
    0% {
      transform: translateY(0px);
    }
    50% {
      transform: translateY(-10px);
    }
    100% {
      transform: translateY(0px);
    }
  }
  
  .group:hover > div {
    animation: float 3s ease-in-out infinite;
  }
  </style>